package com.zlc.common.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.zlc.common.util.DateUtils;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

public class JsonDateDeserialize extends JsonDeserializer<Date> {

    private final String[] patterns = {"yyyy-MM-dd HH:mm:ss","yyyy/MM/dd HH:mm:ss","yyyy-MM-dd","yyyy/MM/dd","yyyy-MM-dd HH:mm"};

    @Override
    public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        String dateAsString = jp.getText();
        Date parseDate = null;
        try {
            parseDate = DateUtils.parseDate(dateAsString, patterns);
        } catch (ParseException e) {
            //如果是数字
            try {
                long time = Long.parseLong(dateAsString);
                return new Date(time);
            }catch (Exception e1){
                throw new IllegalArgumentException(e.getCause());
            }
        }
        return parseDate;
    }


}